<?php

require_once __DIR__.'/vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 创建数据库连接
try {
    $pdo = new PDO(
        "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']};charset=utf8mb4",
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    echo "✅ 数据库连接成功\n";

    // 检查并创建缺失的表
    $tables = [
        'menus',
        'functions',
        'permission_nodes',
        'function_permissions',
        'role_function_permissions'
    ];

    foreach ($tables as $table) {
        $result = $pdo->query("SHOW TABLES LIKE '$table'");
        if ($result->rowCount() == 0) {
            echo "❌ 表 $table 不存在，正在创建...\n";
            createTable($pdo, $table);
        } else {
            echo "✅ 表 $table 已存在\n";
        }
    }

    // 清除现有数据
    echo "🧹 清除现有菜单数据...\n";
    $pdo->exec("DELETE FROM role_function_permissions");
    $pdo->exec("DELETE FROM function_permissions");
    $pdo->exec("DELETE FROM functions");
    $pdo->exec("DELETE FROM permission_nodes");
    $pdo->exec("DELETE FROM menus");

    // 插入菜单数据
    echo "📝 插入菜单数据...\n";
    insertMenuData($pdo);

    echo "🎉 菜单数据修复完成！\n";

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}

function createTable($pdo, $tableName) {
    switch ($tableName) {
        case 'menus':
            $pdo->exec("
                CREATE TABLE menus (
                    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    code VARCHAR(100) NOT NULL UNIQUE,
                    name VARCHAR(100) NOT NULL,
                    path VARCHAR(200) NULL,
                    component VARCHAR(100) NULL,
                    icon VARCHAR(50) NULL,
                    description TEXT NULL,
                    status ENUM('active', 'inactive') DEFAULT 'active',
                    is_visible BOOLEAN DEFAULT TRUE,
                    sort_order INT DEFAULT 0,
                    created_at TIMESTAMP NULL,
                    updated_at TIMESTAMP NULL,
                    INDEX idx_code_status (code, status),
                    INDEX idx_status_visible (status, is_visible),
                    INDEX idx_sort_order (sort_order)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            break;

        case 'functions':
            $pdo->exec("
                CREATE TABLE functions (
                    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    code VARCHAR(100) NOT NULL UNIQUE,
                    name VARCHAR(100) NOT NULL,
                    level ENUM('core', 'optional') DEFAULT 'optional',
                    menu_id BIGINT UNSIGNED NOT NULL,
                    description TEXT NULL,
                    dependencies JSON NULL,
                    status ENUM('active', 'inactive') DEFAULT 'active',
                    sort_order INT DEFAULT 0,
                    created_at TIMESTAMP NULL,
                    updated_at TIMESTAMP NULL,
                    FOREIGN KEY (menu_id) REFERENCES menus(id) ON DELETE CASCADE,
                    INDEX idx_menu_level (menu_id, level),
                    INDEX idx_code_status (code, status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            break;

        case 'permission_nodes':
            $pdo->exec("
                CREATE TABLE permission_nodes (
                    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    code VARCHAR(150) NOT NULL UNIQUE,
                    name VARCHAR(100) NOT NULL,
                    type ENUM('page', 'api', 'field') NOT NULL,
                    resource VARCHAR(200) NULL,
                    description TEXT NULL,
                    status ENUM('active', 'inactive') DEFAULT 'active',
                    created_at TIMESTAMP NULL,
                    updated_at TIMESTAMP NULL,
                    INDEX idx_code_status (code, status),
                    INDEX idx_type_status (type, status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            break;

        case 'function_permissions':
            $pdo->exec("
                CREATE TABLE function_permissions (
                    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    function_id BIGINT UNSIGNED NOT NULL,
                    permission_node_id BIGINT UNSIGNED NOT NULL,
                    created_at TIMESTAMP NULL,
                    updated_at TIMESTAMP NULL,
                    FOREIGN KEY (function_id) REFERENCES functions(id) ON DELETE CASCADE,
                    FOREIGN KEY (permission_node_id) REFERENCES permission_nodes(id) ON DELETE CASCADE,
                    UNIQUE KEY unique_function_permission (function_id, permission_node_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            break;

        case 'role_function_permissions':
            $pdo->exec("
                CREATE TABLE role_function_permissions (
                    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    role_id BIGINT UNSIGNED NOT NULL,
                    function_id BIGINT UNSIGNED NOT NULL,
                    auto_granted BOOLEAN DEFAULT FALSE,
                    granted_by BIGINT UNSIGNED NULL,
                    granted_at TIMESTAMP NULL,
                    created_at TIMESTAMP NULL,
                    updated_at TIMESTAMP NULL,
                    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
                    FOREIGN KEY (function_id) REFERENCES functions(id) ON DELETE CASCADE,
                    UNIQUE KEY unique_role_function (role_id, function_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            break;
    }
}

function insertMenuData($pdo) {
    $now = date('Y-m-d H:i:s');

    // 插入菜单
    $menus = [
        ['user_management', '用户管理', '/user', 'UserManagement', 'user', '管理系统用户账户', 1],
        ['role_management', '角色管理', '/role', 'RoleManagement', 'team', '管理系统角色和权限', 2],
        ['permission_management', '权限管理', '/permission', 'PermissionManagement', 'lock', '管理系统权限节点', 3],
        ['menu_management', '菜单管理', '/menu', 'MenuManagement', 'bars', '管理系统菜单结构', 4],
        ['employee_management', '员工管理', '/employee', 'EmployeeManagement', 'idcard', '管理员工基础信息', 5],
        ['department_management', '组织架构', '/department', 'DepartmentManagement', 'apartment', '管理部门和岗位', 6]
    ];

    $menuIds = [];
    foreach ($menus as $menu) {
        $stmt = $pdo->prepare("
            INSERT INTO menus (code, name, path, component, icon, description, sort_order, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([...$menu, $now, $now]);
        $menuIds[$menu[0]] = $pdo->lastInsertId();
    }

    // 插入功能
    $functions = [
        // 用户管理功能
        ['user_management.list', '用户列表显示', 'core', $menuIds['user_management'], '查看用户列表', null, 1],
        ['user_management.create', '创建用户', 'optional', $menuIds['user_management'], '创建新用户', json_encode([$menuIds['user_management']]), 2],
        ['user_management.edit', '编辑用户', 'optional', $menuIds['user_management'], '编辑用户信息', json_encode([$menuIds['user_management']]), 3],
        ['user_management.delete', '删除用户', 'optional', $menuIds['user_management'], '删除用户', json_encode([$menuIds['user_management']]), 4],
        ['user_management.role_assign', '用户角色分配', 'optional', $menuIds['user_management'], '管理用户角色关联', json_encode([$menuIds['user_management'], $menuIds['role_management']]), 5],

        // 角色管理功能
        ['role_management.list', '角色列表显示', 'core', $menuIds['role_management'], '查看角色列表', null, 1],
        ['role_management.create', '创建角色', 'optional', $menuIds['role_management'], '创建新角色', json_encode([$menuIds['role_management']]), 2],
        ['role_management.edit', '编辑角色', 'optional', $menuIds['role_management'], '编辑角色信息', json_encode([$menuIds['role_management']]), 3],
        ['role_management.delete', '删除角色', 'optional', $menuIds['role_management'], '删除角色', json_encode([$menuIds['role_management']]), 4],

        // 权限管理功能
        ['permission_management.list', '权限节点列表', 'core', $menuIds['permission_management'], '查看权限节点列表', null, 1],
        ['permission_management.create', '创建权限节点', 'optional', $menuIds['permission_management'], '创建新的权限节点', json_encode([$menuIds['permission_management']]), 2],
        ['permission_management.edit', '编辑权限节点', 'optional', $menuIds['permission_management'], '编辑权限节点信息', json_encode([$menuIds['permission_management']]), 3],
        ['permission_management.delete', '删除权限节点', 'optional', $menuIds['permission_management'], '删除权限节点', json_encode([$menuIds['permission_management']]), 4],

        // 菜单管理功能
        ['menu_management.list', '菜单列表', 'core', $menuIds['menu_management'], '查看菜单列表', null, 1],
        ['menu_management.create', '创建菜单', 'optional', $menuIds['menu_management'], '创建新菜单项', json_encode([$menuIds['menu_management']]), 2],
        ['menu_management.edit', '编辑菜单', 'optional', $menuIds['menu_management'], '编辑菜单信息', json_encode([$menuIds['menu_management']]), 3],
        ['menu_management.delete', '删除菜单', '可选', $menuIds['menu_management'], '删除菜单项', json_encode([$menuIds['menu_management']]), 4]
    ];

    foreach ($functions as $function) {
        $stmt = $pdo->prepare("
            INSERT INTO functions (code, name, level, menu_id, description, dependencies, sort_order, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([...$function, $now, $now]);
    }

    echo "✅ 菜单和功能数据插入完成\n";
}
